<?php


/**
* CakePHP Routines Plugin
* http://cake-routines-plugin.googlecode.com
*
* @package routines
* @subpackage routines.models.behaviors
* @author Ivan Chistyakov <zetruger@gmail.com>
* @version $Id: attachable.php 167 2010-10-22 07:13:36Z zetruger@gmail.com $
* @link $HeadURL: http://cake-routines-plugin.googlecode.com/svn/trunk/models/behaviors/attachable.php $
* @license MIT License (http://opensource.org/licenses/mit-license.php)
*/


class AttachableBehavior extends ModelBehavior {

var $_defaults = array(
	'attachModelField' => 'model',
	'attachModelValue' => NULL,
	'attachForeignKeyField' => 'foreign_key',
	'attachForeignKeyValue' => NULL,
	'useRequestParams' => TRUE,
	'useRequestNamedParams' => FALSE
);

var $settings = array();

function setup(&$Model, $settings = array()) {
	$this->settings[$Model->alias] = $settings;
}

function _getSettings(&$Model, $settings = array()) {
	$settings = Set::merge($this->settings[$Model->alias], $settings);
	if (isset($settings['noUseModelVars']) && $settings['noUseModelVars']) {
		return Set::merge($this->_defaults, $settings);
	} else {
		return Set::merge($this->_defaults, array_intersect_key(get_object_vars($Model), $this->_defaults), $settings);
	}
}

function _getRequestSettings(&$Model, $settings = array()) {
	extract($settings = $this->_getSettings($Model), EXTR_SKIP);
	$requestParams = Router::getParams(TRUE);
	if (Inflector::tableize($Model->alias) == $requestParams['controller']) {
		if ($useRequestParams && isset($requestParams[$attachModelField], $requestParams[$attachForeignKeyField])) {
			$settings['attachModelValue'] = $requestParams[$attachModelField];
			$settings['attachForeignKeyValue'] = $requestParams[$attachForeignKeyField];
		} elseif ($useRequestNamedParams && isset($requestParams['named'][$attachModelField], $requestParams['named'][$attachForeignKeyField])) {
			$settings['attachModelValue'] = $requestParams['named'][$attachModelField];
			$settings['attachForeignKeyValue'] = $requestParams['named'][$attachForeignKeyField];
		}
	}
	return $settings;
}

function beforeFind(&$Model, $query) {
	extract($this->_getRequestSettings($Model), EXTR_SKIP);
	if ($Model->hasField(array($attachModelField, $attachForeignKeyField)) && !is_null($attachModelValue) && !is_null($attachForeignKeyValue)) {
		$query['conditions'][$Model->escapeField($attachModelField)] = $attachModelValue;
		$query['conditions'][$Model->escapeField($attachForeignKeyField)] = $attachForeignKeyValue;
	}
	return $query;
}

function beforeSave(&$Model) {
	extract($this->_getRequestSettings($Model), EXTR_SKIP);
	if ($Model->hasField(array($attachModelField, $attachForeignKeyField)) && !is_null($attachModelValue) && !is_null($attachForeignKeyValue)) {
		$Model->data[$Model->alias][$attachModelField] = $attachModelValue;
		$Model->data[$Model->alias][$attachForeignKeyField] = $attachForeignKeyValue;
	}
	return TRUE;
}

}


?>